package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityHandleAdressBinding;
import com.sgb.kjwl.model.entity.transport.GoodsSourcePlace;
import com.sgb.kjwl.model.entity.transport.common.AddressItem;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.transport.HandleAddressAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.HandleAdressViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/3/1
 * @Description: 货源装卸地点地图
 */
public class HandleAdressActivity extends AppActivity {
    HandleAdressViewModel viewModel;
    ActivityHandleAdressBinding binding;
    private AMap aMap;
    Bundle savedInstanceState;
    private MapMarkerTools mapMarkerTools;
    HandleAddressAdapter addressAdapter;
    List<MarkerEntity> markerEntityList = new ArrayList<>();
    private List<LatLonPoint> sourcePoints = new ArrayList<>();
    List<AddressItem> bundles = new ArrayList<>();
    List<Marker> markers = new ArrayList<>();
    private Marker markerLast;
    private int lastPosition;
    private int pos;
    private String tel, imaccount;

    public static void start(Context context, String name, String company, String tel, String imAccount, GoodsSourcePlace placeinfo, int pos, String handleType) {
        Intent intent = new Intent(context, HandleAdressActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("company", company);
        intent.putExtra("tel", tel);
        intent.putExtra("imaccount", imAccount);
        intent.putExtra("placeinfo", placeinfo);
        intent.putExtra("pos", pos);
        intent.putExtra("handleType", handleType);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
//        DaggerTransportComponent.builder().appComponent(appComponent).transportModule(new TransportModule(this)).build().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;

    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_handle_adress);
        viewModel = new ViewModelProvider(this).get(HandleAdressViewModel.class);
        mapMarkerTools = new MapMarkerTools(getActivity(), getLifecycle(), false);
        mapMarkerTools.init(savedInstanceState, binding.mapView);
        binding.include.titleView.setText("装卸货地点");
        binding.include.ivBack.setOnClickListener(v -> {
            finish();
        });
        binding.tvMsg.setOnClickListener(this);
        binding.tvTel.setOnClickListener(this);
        aMap = binding.mapView.getMap();
        viewModel.setAMap(aMap);
        binding.rlList.setLayoutManager(new LinearLayoutManager(this));
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                if (marker.getObject() != null) {
                    AddressItem item = (AddressItem) marker.getObject();

                    for (int i = 0; i < bundles.size(); i++) {
                        if (item.getPosition() == i) {
                            if (bundles.get(i).isBigMarkView()) {
                                setMarkStyle(i, marker, false);
                                addressAdapter.setSelect(-1);
                            } else {
                                setMarkStyle(i, marker, true);
                                addressAdapter.setSelect(i);
                            }
                            if (lastPosition != i) {
                                resetMarker(lastPosition);
                            }
                            markerLast = marker;
                            lastPosition = i;

                            break;
                        }
                    }

                }
                return false;
            }
        });
        getData();
    }

    private void getData() {
        String name = getIntent().getStringExtra("name");
        String company = getIntent().getStringExtra("company");
        tel = getIntent().getStringExtra("tel");
        imaccount = getIntent().getStringExtra("imaccount");
        GoodsSourcePlace mgoodsSourcePkace = (GoodsSourcePlace) getIntent().getSerializableExtra("placeinfo");
        pos = getIntent().getIntExtra("pos", 0);
        String handleTypeNo = getIntent().getStringExtra("handleType");
        binding.tvName.setText(name);
        binding.tvAdress.setText(company);
        List<AddressItem> list = new ArrayList<>();
        if ("11".equals(handleTypeNo)) {//一装一卸
            list.add(new AddressItem(mgoodsSourcePkace.getProvinceName() + "  " + mgoodsSourcePkace.getCityName() + "  " + mgoodsSourcePkace.getDistrictName(), mgoodsSourcePkace.getDetailAddress(), R.mipmap.icon_load_goods, mgoodsSourcePkace.getLatitude(), mgoodsSourcePkace.getLongitude(), R.mipmap.icon_samll_handle, R.mipmap.icon_big_handle));
            list.add(new AddressItem(mgoodsSourcePkace.getDestProvinceName() + "  " + mgoodsSourcePkace.getDestCityName() + "  " + mgoodsSourcePkace.getDestDistrictName(), mgoodsSourcePkace.getDestDetailAddress(), R.mipmap.icon_unload_goods, mgoodsSourcePkace.getDestLatitude(), mgoodsSourcePkace.getDestLongitude(), R.mipmap.icon_unload, R.mipmap.icon_big_unload));
        } else if ("12".equals(handleTypeNo)) {//一装两卸
            list.add(new AddressItem(mgoodsSourcePkace.getProvinceName() + "  " + mgoodsSourcePkace.getCityName() + "  " + mgoodsSourcePkace.getDistrictName(), mgoodsSourcePkace.getDetailAddress(), R.mipmap.icon_load_goods, mgoodsSourcePkace.getLatitude(), mgoodsSourcePkace.getLongitude(), R.mipmap.icon_samll_handle, R.mipmap.icon_big_handle));
            list.add(new AddressItem(mgoodsSourcePkace.getViaDestProvinceName() + "  " + mgoodsSourcePkace.getViaDestCityName() + "  " + mgoodsSourcePkace.getViaDestDistrictName(), mgoodsSourcePkace.getViaDestDetailAddress(), R.mipmap.icon_unload_one, mgoodsSourcePkace.getViaDestLatitude(), mgoodsSourcePkace.getViaDestLongitude(), R.mipmap.icon_unload1, R.mipmap.icon_big_unload1));
            list.add(new AddressItem(mgoodsSourcePkace.getDestProvinceName() + "  " + mgoodsSourcePkace.getDestCityName() + "  " + mgoodsSourcePkace.getDestDistrictName(), mgoodsSourcePkace.getDestDetailAddress(), R.mipmap.icon_unload_two, mgoodsSourcePkace.getDestLatitude(), mgoodsSourcePkace.getDestLongitude(), R.mipmap.icon_unload2, R.mipmap.icon_big_unload2));
        } else if ("21".equals(handleTypeNo)) {//两装一卸
            list.add(new AddressItem(mgoodsSourcePkace.getProvinceName() + "  " + mgoodsSourcePkace.getCityName() + "  " + mgoodsSourcePkace.getDistrictName(), mgoodsSourcePkace.getDetailAddress(), R.mipmap.icon_load_one, mgoodsSourcePkace.getLatitude(), mgoodsSourcePkace.getLongitude(), R.mipmap.icon_samll_handle1, R.mipmap.icon_big_handle1));
            list.add(new AddressItem(mgoodsSourcePkace.getViaSendProvinceName() + "  " + mgoodsSourcePkace.getViaSendCityName() + "  " + mgoodsSourcePkace.getViaSendDistrictName(), mgoodsSourcePkace.getViaSendDetailAddress(), R.mipmap.icon_load_two, mgoodsSourcePkace.getViaSendLatitude(), mgoodsSourcePkace.getViaSendLongitude(), R.mipmap.icon_samll_handle2, R.mipmap.icon_big_handle2));
            list.add(new AddressItem(mgoodsSourcePkace.getDestProvinceName() + "  " + mgoodsSourcePkace.getDestCityName() + "  " + mgoodsSourcePkace.getDestDistrictName(), mgoodsSourcePkace.getDestDetailAddress(), R.mipmap.icon_unload_goods, mgoodsSourcePkace.getDestLatitude(), mgoodsSourcePkace.getDestLongitude(), R.mipmap.icon_unload, R.mipmap.icon_big_unload));
        } else if ("22".equals(handleTypeNo)) {
            list.add(new AddressItem(mgoodsSourcePkace.getProvinceName() + "  " + mgoodsSourcePkace.getCityName() + "  " + mgoodsSourcePkace.getDistrictName(), mgoodsSourcePkace.getDetailAddress(), R.mipmap.icon_load_one, mgoodsSourcePkace.getLatitude(), mgoodsSourcePkace.getLongitude(), R.mipmap.icon_samll_handle1, R.mipmap.icon_big_handle1));
            list.add(new AddressItem(mgoodsSourcePkace.getViaSendProvinceName() + "  " + mgoodsSourcePkace.getViaSendCityName() + "  " + mgoodsSourcePkace.getViaSendDistrictName(), mgoodsSourcePkace.getViaSendDetailAddress(), R.mipmap.icon_load_two, mgoodsSourcePkace.getViaSendLatitude(), mgoodsSourcePkace.getViaSendLongitude(), R.mipmap.icon_samll_handle2, R.mipmap.icon_big_handle2));
            list.add(new AddressItem(mgoodsSourcePkace.getViaDestProvinceName() + "  " + mgoodsSourcePkace.getViaDestCityName() + "  " + mgoodsSourcePkace.getViaDestDistrictName(), mgoodsSourcePkace.getViaDestDetailAddress(), R.mipmap.icon_unload_one, mgoodsSourcePkace.getViaSendLatitude(), mgoodsSourcePkace.getViaSendLongitude(), R.mipmap.icon_unload1, R.mipmap.icon_big_unload1));
            list.add(new AddressItem(mgoodsSourcePkace.getDestProvinceName() + "  " + mgoodsSourcePkace.getDestCityName() + "  " + mgoodsSourcePkace.getDestDistrictName(), mgoodsSourcePkace.getDestDetailAddress(), R.mipmap.icon_unload_two, mgoodsSourcePkace.getDestLatitude(), mgoodsSourcePkace.getDestLongitude(), R.mipmap.icon_unload2, R.mipmap.icon_big_unload2));
        }
        addressAdapter = new HandleAddressAdapter(list);
        binding.rlList.setAdapter(addressAdapter);
        binding.rlList.smoothScrollToPosition(pos);
        addressAdapter.setSelect(pos);
        addressAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int pos) {
                addressAdapter.setSelect(pos);
                LatLng currentLatLng = new LatLng(list.get(pos).getLatitude(), list.get(pos).getLongitude());
                setMarkStyle(pos, markers.get(pos), true);
                if (pos != lastPosition) {
                    resetMarker(lastPosition);
                }
                markerLast = markers.get(pos);
                lastPosition = pos;
                mapMarkerTools.mapMoveCamera(currentLatLng, 11);
            }
        });
        addMarker(list);
        LatLng currentLatLng = new LatLng(list.get(pos).getLatitude(), list.get(pos).getLongitude());
        markerLast = markers.get(pos);
        setMarkStyle(pos, markerLast, true);
        lastPosition = pos;
        mapMarkerTools.mapMoveCamera(currentLatLng, 11);
    }

    private void addMarker(List<AddressItem> list) {
        sourcePoints.clear();
        aMap.clear();
        for (int i = 0; i < list.size(); i++) {
            AddressItem entity = list.get(i);
            entity.setPosition(i);
            LatLng latLng = new LatLng(entity.getLatitude(), entity.getLongitude());
            LatLonPoint latLonPoint = new LatLonPoint(entity.getLatitude(), entity.getLongitude());
            sourcePoints.add(latLonPoint);
            MarkerEntity markerEntity;
            markerEntity = new MarkerEntity(latLng, entity.getMakerIcon(), "");
            bundles.add(entity);
            markerEntityList.add(markerEntity);

        }
        for (int i = 0; i < markerEntityList.size(); i++) {
            Marker marker = aMap.addMarker(mapMarkerTools.getMarkerOptions(markerEntityList.get(i)));
            marker.setObject(bundles.get(i));
            markers.add(marker);
        }
        viewModel.planningLoadingRoute(this, sourcePoints);
    }

    //设置maker大小图标
    private void setMarkStyle(int pos, Marker marker, boolean isBigMarkView) {
        AddressItem entity = bundles.get(pos);
        BitmapDescriptor bitmapSmall = null;

        bitmapSmall = isBigMarkView ? BitmapDescriptorFactory.fromResource(entity.getBigMakerIcon()) : BitmapDescriptorFactory.fromResource(entity.getMakerIcon());
        entity.setBigMarkView(isBigMarkView);
        marker.setIcon(bitmapSmall);
    }

    private void resetMarker(int pos) {
        AddressItem entity = bundles.get(pos);
        markerLast.setIcon(BitmapDescriptorFactory.fromResource(entity.getMakerIcon()));
        entity.setBigMarkView(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_msg:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(this);
                    return;
                }
                if (!TextUtils.isEmpty(imaccount)) {
                    // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                    buildSingleTalking(imaccount);
                }
                break;
            case R.id.tv_tel:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(this);
                    return;
                }
                new RoundDialog.Builder(this)
                        .title("确认呼叫")
                        .content(tel)
                        .cancel("取消")
                        .confirm("确定")
                        .contentGravity(Gravity.CENTER)
                        .cancelable(false)
                        .confirmCallback(new RoundDialog.SingleCallback() {
                            @Override
                            public void onClick(View v) {
                                callPhone(tel);
                            }
                        })
                        .show();
                break;
        }
    }
}
